package com.baihejia.common.dubbo.server;

import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.zookeeper.ZookeeperConfigGroup;
import com.dangdang.config.service.zookeeper.ZookeeperConfigProfile;

import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

public class Configuration {

    static Properties properties = new Properties();
    static Properties systemProperties = new Properties();
    static String env = null;
    public static void init() {
        try {
            InputStream in = Configuration.class.getClassLoader().getResourceAsStream("application.conf");
            systemProperties.load(in);

            env = systemProperties.getProperty("env");
            if (env.equals("${env}")) {
                env = "dev";
            }

            String keyPrefix = "%" + env + ".";
            Set<Object> systemKeys = systemProperties.keySet().stream().filter(key -> ((String) key).startsWith(keyPrefix)).collect(Collectors.toSet());

            systemProperties.keySet().stream().filter(key -> !systemKeys.contains(key)).forEach(key -> {
                properties.put(key, systemProperties.getProperty((String)key));
            });

            in.close();
            
            properties.put("env", env);

            for (Object systemKey : systemKeys) {
                properties.put(((String)systemKey).replaceFirst(keyPrefix, ""), systemProperties.getProperty((String)systemKey));
            }

            ZookeeperConfigProfile configProfile = new ZookeeperConfigProfile(get("zkHosts"), get("zkNode"), get("zkVer"));
            GeneralConfigGroup group = new ZookeeperConfigGroup(configProfile, get("zkGroup"));

            for (Map.Entry<String, String> entry : group.entrySet()) {
                properties.put(entry.getKey(), entry.getValue());
            }

            System.out.println("properties loaded:" + properties);

            group.register(properties::put);
        } catch (Exception e) {
        	e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static String get(String key) {
        return properties.getProperty(key);
    }

    public static boolean isTest() {
        return env.equals("test");
    }
}
